const db = uniCloud.database();
const student_collection = db.collection('student');
const relative_collection = db.collection('relative');

module.exports = {
	_before() {
		// 可以在这里添加一些前置通用逻辑，当前为空
	},
	/**
	 * 获取学生信息
	 * @returns {object[]} 返回包含学生信息以及关联亲属信息的数组
	 */
	async getStudentInfo() {
		const students = await student_collection.get();
		const studentsWithRelative = [];

		for (let student of students.data) {
			const relative = await relative_collection.where({
				student_id: student.id
			}).get();
			student.relative = relative.data;
			studentsWithRelative.push(student);
		}

		return studentsWithRelative;
	},

	/**
	 * 添加学生信息
	 */
	async addStudentInfo(studentData) {
		// 从传入的 studentData 中解构(提取)出 relative 数组
		const {
			relative = []
		} = studentData;
		try {
			// 移除传入的studentData中的id/relative字段，并单独赋值给id/relative
			const {
				id,
				relative,
				...newStudentData
			} = studentData;

			// 检查student表中是否存在相同name的条目
			const studentSnapshot = await student_collection.where({
				name: newStudentData.name
			}).get();
			console.log('studentSnapshot length', studentSnapshot.data.length > 0);
			if (studentSnapshot.data.length > 0) {
				console.log('已有相同名字的学生存在，添加失败');
				return;
			}

			// 添加student表中的id，区分功能：_id用于云数据库操作，id可后续用于本地数据
			// 获取student表中最后一条数据的id
			const lastStudent = await student_collection.orderBy('id', 'desc').limit(1).get();
			let student_newId;
			if (lastStudent.data.length > 0) {
				const lastId = lastStudent.data[0].id;
				student_newId = lastId + 1;
			} else {
				student_newId = 111111;
			}

			// 添加relative表中的id，区分功能：_id用于云数据库操作，id可后续用于本地数据
			// 获取relative表中最后一条数据的id
			const lastRelative = await relative_collection.orderBy('id', 'desc').limit(1).get();
			let relative_newId;
			if (lastRelative.data.length > 0) {
				const lastId = lastStudent.data[0].id;
				relative_newId = lastId + 1;
			} else {
				relative_newId = 999999;
			}

			const newStudentData_id = {
				...newStudentData,
				id: student_newId
			};
			// 先添加学生信息，数据库会自动生成_id
			const studentRes = await student_collection.add(newStudentData_id);
			const studentId = studentRes.id; //studentRes.id对应数据表中的_id

			// 遍历亲属数据，为每个亲属记录添加关联的学生_id
			for (const relativeItem of relative) {
				const new_relativeItem = {
					...relativeItem,
					id: relative_newId,
					student_id: studentId
				};
				await relative_collection.add(new_relativeItem);
			}
		} catch (error) {
			throw new Error('添加学生信息失败:' + error.message);
		}
	},
	/**
	 * 根据id获取单个学生信息
	 * @param {string|number} id - 学生的id
	 * @returns {object} 返回单个学生信息及其关联亲属信息
	 */
	async getStudentById(id) {
		const student = await student_collection.where({
			_id: id
		}).get();
		if (student.data.length === 0) {
			return;
		}

		const relative = await relative_collection.where({
			student_id: id
		}).get();
		student.data[0].relative = relative.data;

		return student.data[0];
	},
	/**
	 * 根据studentId更新student信息
	 * @param {string|number} studentId - 学生的id
	 * @param {object} newStudentData - 包含全新学生数据的对象
	 */
	async updateStudent(studentData) {
		try {
			// 移除传入的studentData中的relative字段，并单独赋值给relative
			const {
				relative,
				...newStudentData
			} = studentData;
			const studentId = newStudentData._id;

			// 更新student表信息
			const studentRes = await student_collection.doc(studentId).set(newStudentData, {
				merge: true
			});

			// 更新亲属信息
			for (const rel of relative) {
				const relativeQuery = await relative_collection.where({
					student_id: studentId,
					name: rel.name
				}).get();
				console.log('relative', relative);
				console.log('relativeQuery', relativeQuery);
				console.log('rel', rel);
				if (relativeQuery.data.length > 0) {
					// 存在则更新
					const relativeId = relativeQuery.data[0]._id;
					await relative_collection.doc(relativeId).set(rel, {
						merge: true
					});
				} else {
					// 不存在则新增
					const lastRelative = await relative_collection.orderBy('id', 'desc').limit(1).get();
					let relative_newId;
					if (lastRelative.data.length > 0) {
						relative_newId = lastRelative.data[0].id + 1;
					} else {
						relative_newId = 888888;
					}
					const newRelative = {
						...rel,
						id: relative_newId++,
						student_id: studentId
					};
					console.log('newRelative', newRelative);
					await relative_collection.add(newRelative);
				}
			}
		} catch (error) {
			throw new Error('更新学生信息失败:' + error.message);
		}
	},
	/**
	 * 根据ID删除学生信息及其关联亲属信息
	 * @param {string|number} id - 学生的id
	 */
	async removeStudentById(id) {
		try {
			// 先删除亲属信息
			const relativeDeleteRes = await relative_collection.where({
				student_id: id
			}).remove();
			console.log('亲属信息删除结果:', relativeDeleteRes);

			// 再删除学生信息,doc方法对应的是_id
			const studentDeleteRes = await student_collection.doc(id).remove();
			console.log('学生信息删除结果:', studentDeleteRes);
		} catch (error) {
			throw new Error('删除学生信息失败:' + error.message);
		}
	}

};